package uploader

import (
	"fmt"
	"github.com/google/uuid"
	"io"
	"net/http"
	"os"
	"path/filepath"
	file2 "server/file"
	"server/response"
)

type DirectUploader struct {
	filePath string
}

func (d *DirectUploader) HandleUpload(w http.ResponseWriter, r *http.Request) {
	res := &response.Response{}
	if r.Method != http.MethodPost {
		res.MethodNotAllowed(w)
		return
	}
	file, fileHeader, err := r.FormFile("file")

	if err != nil {
		res.BadRequest(w, "file 字段不存在")
		fmt.Println(err)
		return
	}

	fid := uuid.New().String()
	file2.FileStorage[fid] = fileHeader.Filename

	ext := filepath.Ext(fileHeader.Filename)
	path := filepath.Join(d.filePath, fid+ext)
	var dst *os.File
	dst, err = os.Create(path)
	if err != nil {
		res.ServerErr(w, "保存文件失败")
		fmt.Println(err)
		return
	}

	_, err = io.Copy(dst, file)
	if err != nil {
		res.ServerErr(w, "保存文件失败")
		fmt.Println(err)
		return
	}
	res.RespOk(w, &file2.FileMeta{
		Fid:  fid,
		Name: fileHeader.Filename,
	})

	defer func() {
		_ = file.Close()
		_ = dst.Close()
		res.Send(w)
	}()
}

func NewDirectUploader(path string) *DirectUploader {
	return &DirectUploader{
		filePath: path,
	}
}
